package com.alibaba.moco.util;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.dto.CallbackDidiPayRequest;
import com.alibaba.dto.CallbackRequest;
import com.alibaba.dto.CallbackResponse;

import net.sf.json.JSONObject;

public class HttpClientUtil {

	private static String HTTP="http://";
	private static String HXIP="hx_ip";
	private static String SYMBOL=":";
	private static String HXPROT="hx_prot";
	
	
	private static String HXPOSTADDRESS="hx_post_address";
	private static String HXPAYPOSTADDRESS="hx_paypost_address";
	
	
	public static void post(final CallbackRequest requestData){
		
		CallbackResponse result = postForm(requestData);

		if(result==null || !result.getErrno().equals(0)){
    		
    		Runnable runnable = new Runnable() {  
                public void run() {  
                	HttpClientUtil.postForm(requestData);
                }  
            };  
            ScheduledExecutorService service = Executors  
                    .newSingleThreadScheduledExecutor();  
            
            service.schedule(runnable, 5, TimeUnit.SECONDS);
			
    	}else{
    		System.out.println("第一次回调成功!");
    	}
	}
	
	public static void postPay(final CallbackDidiPayRequest requestData){
		
		CallbackResponse result = postPayForm(requestData);

		if(result==null || !result.getErrno().equals(0)){
    		
    		Runnable runnable = new Runnable() {  
                public void run() {  
                	HttpClientUtil.postPayForm(requestData);
                }  
            };  
            ScheduledExecutorService service = Executors  
                    .newSingleThreadScheduledExecutor();  
            
            service.schedule(runnable, 5, TimeUnit.SECONDS);
			
    	}else{
    		System.out.println("第一次回调成功!");
    	}
	}
	
	
	public static CallbackResponse postForm(CallbackRequest requestData){
		
		// 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        
        StringBuffer URL = new StringBuffer(HTTP);
	        URL.append(PropertiesUtils.getAttribute(HXIP));
	        URL.append(SYMBOL);
	        URL.append(PropertiesUtils.getAttribute(HXPROT));
	        URL.append(PropertiesUtils.getAttribute(HXPOSTADDRESS));
        
        System.out.println(URL);
        // 创建httppost    
        HttpPost httppost = new HttpPost(URL.toString());  
        // 创建参数队列    
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
        formparams.add(new BasicNameValuePair("client_id", requestData.getClientId()));
        formparams.add(new BasicNameValuePair("order_id", requestData.getOrderId()));
        formparams.add(new BasicNameValuePair("notify_type", String.valueOf(requestData.getNotifyType())));
        formparams.add(new BasicNameValuePair("notify_desc", requestData.getNotifyDesc()));
        formparams.add(new BasicNameValuePair("timestamp", String.valueOf(requestData.getTimestamp()) ));
        																									
        formparams.add(new BasicNameValuePair("sign", requestData.getSign()));

        UrlEncodedFormEntity uefEntity; 
        CallbackResponse result = null;
        try {  
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
            httppost.setEntity(uefEntity);  
            CloseableHttpResponse response = httpclient.execute(httppost);  
            
            try {  
                HttpEntity entity = response.getEntity(); 
                
                if (entity != null) {  
                	
                	String jsonStr = EntityUtils.toString(entity, "UTF-8");
                	result = (CallbackResponse) JSONObject.toBean(JSONObject.fromObject(jsonStr)//
                												 ,CallbackResponse.class);
                	
                	System.out.println("执行 postForm ...." + result.toString());
                } 
            } finally {  
                response.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        
        return result;
	}
	
	
	public static CallbackResponse postPayForm(CallbackDidiPayRequest requestData){
		
		// 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();  

        StringBuffer URL = new StringBuffer(HTTP);
	        URL.append(PropertiesUtils.getAttribute(HXIP));
	        URL.append(SYMBOL);
	        URL.append(PropertiesUtils.getAttribute(HXPROT));
	        URL.append(PropertiesUtils.getAttribute(HXPAYPOSTADDRESS));
        
        System.out.println(URL);
        
        // 创建httppost    
        HttpPost httppost = new HttpPost(URL.toString());  
        // 创建参数队列    
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
        formparams.add(new BasicNameValuePair("client_id", requestData.getClientId()));
        formparams.add(new BasicNameValuePair("client_secret", requestData.getClientSecret()));
        formparams.add(new BasicNameValuePair("order_id", requestData.getOrderId()));
        formparams.add(new BasicNameValuePair("normal_distance", String.valueOf(requestData.getNormalDistance())));
        formparams.add(new BasicNameValuePair("total_price", String.valueOf(requestData.getTotalPrice())));
        formparams.add(new BasicNameValuePair("pay_time", String.valueOf(requestData.getPayTime())));
        formparams.add(new BasicNameValuePair("status", String.valueOf(requestData.getStatus())));
        formparams.add(new BasicNameValuePair("callback_info", requestData.getCallbackInfo()));
        formparams.add(new BasicNameValuePair("timestamp", String.valueOf(requestData.getTimestamp())));
        
        formparams.add(new BasicNameValuePair("sign",  requestData.getSign()));
        
 

        UrlEncodedFormEntity uefEntity; 
        CallbackResponse result = null;
        try {  
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);  
            CloseableHttpResponse response = httpclient.execute(httppost);  
            
            try {  
                HttpEntity entity = response.getEntity(); 
                
                if (entity != null) {  
                	
                	String jsonStr = EntityUtils.toString(entity, "UTF-8");
                	result = (CallbackResponse) JSONObject.toBean(JSONObject.fromObject(jsonStr)//
                												 ,CallbackResponse.class);
                	
                	System.out.println("执行 postPayForm ...." + result.toString());
                } 
            } finally {  
                response.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        
        return result;
	}
	
	
	
	
	public static void main(String[] args) throws IOException{
		Properties prop = new Properties();
		
		InputStream in = Object.class.getResourceAsStream("/config.properties");
		
		prop.load(in);
		
		System.out.println(prop.getProperty("test"));
		
		/*CallbackDidiPayRequest callbackDidiPayRequest = new CallbackDidiPayRequest();

        callbackDidiPayRequest.setClientId("1");
        callbackDidiPayRequest.setSign("1");
        callbackDidiPayRequest.setTimestamp(System.currentTimeMillis());
        callbackDidiPayRequest.setOrderId("6486791125256278016");
        callbackDidiPayRequest.setCallbackInfo("188126,1000662,http://10.101.86.141,9243");
        callbackDidiPayRequest.setClientSecret("123");
        callbackDidiPayRequest.setNormalDistance(1000.0);
        callbackDidiPayRequest.setPayTime(System.currentTimeMillis());
        callbackDidiPayRequest.setStatus(701);
         callbackDidiPayRequest.setTotalPrice(new BigDecimal(100));

        HttpClientUtil.postPay(callbackDidiPayRequest);*/
		
		
		/*CallbackRequest callbackRequest = new CallbackRequest();
        callbackRequest.setClientId("1");
        callbackRequest.setNotifyDesc("正常支付待评论");
        callbackRequest.setNotifyType(2);

        callbackRequest.setOrderId("2940519544822153216");
        callbackRequest.setSign("abcdefg");
        callbackRequest.setTimestamp(123456l);
        HttpClientUtil.postForm(callbackRequest);*/
       
	}
	
	
}
